//
//  TKIMConverseSearchView.m
//  TKIM
//
//  Created by liupm on 15/10/31.
//  Copyright © 2015年 liupm. All rights reserved.
//

#import "TKIMConverseSearchView.h"
#import "TKIMConverseCell.h"
#import "TKIMChatViewController.h"

@implementation TKIMConverseSearchView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TKIMConverseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" ];
    if (!cell){
        cell = [[TKIMConverseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    TKIMConverseMessage *msg = self.resultSource[indexPath.row];
    cell.titleLabel.text = msg.targetUserName;
    if (msg.text&&msg.text.length>0) {
        NSArray *b = [msg.text componentsSeparatedByString:@"|"];
        if (b&&b.count>0) {
            cell.subLabel.text = b[0];
        }
    }
    
    //如果会话置顶
    if (msg.isToTop) {
        cell.contentView.backgroundColor = [TKIMColorHelper stringToColor:@"#EFEFF4"];
    } else {
        cell.contentView.backgroundColor = [UIColor whiteColor];
    }
    
    if (msg.chatUserType == TKIMUserTypeDefault || msg.chatUserType == TKIMUserTypeOfficial) {
        cell.headView.image = TKIMGetImage(@"im_icon_userDefault");
    } else if(msg.chatUserType == TKIMUserTypeSys) {
        
        NSString *url = @"";
        if (msg.photoUrl.length > 0) {
            url = msg.photoUrl;
        }else{
            url = [self getPlistWithKey:msg.targetUserName];
        }
        [cell.headView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:TKIMGetImage(@"IM_black_ic_sysMessage_0")];
        
//        [cell.headView sd_setImageWithURL:[NSURL URLWithString:msg.photoUrl] placeholderImage:TKIMGetImage(@"IM_black_ic_sysMessage_0")];
    }else{
        [cell.headView sd_setImageWithURL:[NSURL URLWithString:msg.photoUrl] placeholderImage:TKIMGetImage(@"IM_black_ic_sysMessage_0")];
    }
    
    cell.time.text = [TKIMDateHelper formattedTime:msg.time];

    return cell;
}


- (NSString *)getIconUrlPath
{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [path objectAtIndex:0];
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"TKIMIconUrl.plist"];
    return plistPath;
}

- (void)savePlistWithKey:(NSString *)key value:(NSString *)value
{
    NSString *plistPath = [self getIconUrlPath];
    NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    
    if (!dataDict) {
        dataDict = [[NSMutableDictionary alloc]init];
    }
    
    [dataDict setObject:value forKey:key];
    [dataDict writeToFile:plistPath atomically:YES];
}

- (NSString *)getPlistWithKey:(NSString *)key
{
    NSString *plistPath = [self getIconUrlPath];
    NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    NSString *urlStr = [dataDict objectForKey:key];
    return urlStr;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TKIMConverseMessage *msg  = self.resultSource[indexPath.row];
    if (msg.chatUserType != TKIMUserTypeRoom
        &&
        msg.chatUserType != TKIMUserTypeGroup)
    {
        TKIMUser *user = [[TKIMUser alloc] init];
        user.userID = msg.targetUser;
        user.nickName = msg.targetUserName;
        
        user.userType = msg.chatUserType;
        if (_searchDelegate &&[_searchDelegate respondsToSelector:@selector(toChat:converse:)])
        {
              [_searchDelegate toChat:user converse:msg];
        }
    }
    else
    {
        TKIMRoom *group = [[TKIMRoom alloc] init];
        group.roomName = msg.targetUserName;
        group.roomId = msg.targetUser;
        group.roomType = msg.chatUserType;
        if (_searchDelegate &&[_searchDelegate respondsToSelector:@selector(toGroup:)])
        {
            [_searchDelegate toGroup:group];
        }
    }
}


-(NSMutableArray *)textDidChange:(NSString *)text
{
    // 按聊天室名称查询会话，返回TKIMMessage数组
    NSArray *byNameArr = [[TKIMManager shareInstance] queryHisConverseByName:text];
    // 按会话内容查询会话，返回TKIMConverseMessage数组
    NSArray *byTextArr = [[TKIMManager shareInstance] queryHisMessageContain:text limit:20];
    NSMutableArray *conversArr = [NSMutableArray array];
    for (int i = 0; i < byTextArr.count; i++) {
        [conversArr addObject:[self getConverseMsg:byTextArr[i]]];
    }
    
    for (TKIMConverseMessage *msg in byNameArr) {
        msg.text =  [TKIMHelper filterMessage:msg.text];
    }
    
//    [conversArr addObjectsFromArray:byNameArr];
    return conversArr;
}



-(TKIMConverseMessage *)getConverseMsg:(TKIMMessage *)msg
{
    if([msg isKindOfClass:[TKIMConverseMessage class]]){
        return (TKIMConverseMessage *)msg;
    }
    TKIMConverseMessage *cMsg = [[TKIMConverseMessage alloc] init];
    cMsg.time = msg.time;
    cMsg.text = [TKIMHelper filterMessage:msg.text];
    cMsg.chatUserType = msg.chatUserType;
    cMsg.type = msg.type;
    cMsg.isRemind = [self isRemind:msg];
    cMsg.targetUser = msg.targetId;
    NSString* tempname =[[TKIMDBManager shareInstance] queryTargetNameById:msg.targetId];
    cMsg.targetUserName =tempname?tempname:msg.targetName;
    cMsg.ext = msg.ext;
    cMsg.refId = msg.refId;
    cMsg.isSender = msg.isSender;
    cMsg.channel = msg.channel;
    cMsg.folder = msg.folder;
    return cMsg;
}
-(BOOL)isRemind:(TKIMMessage *)msg
{
    if (msg.ext)
    {
        NSArray *reminds = msg.ext[@"remind"];
        for (NSDictionary *dic in reminds)
        {
            NSString *uid = dic[@"jid"];
            if ([uid isEqualToString:[TKIMSDKHelper getLoginUserName]])
            {
                return YES;
                break;
            }
        }
    }
    return NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

@end
